/* mixin */
import fieldMixin from '@src/mixins/fieldMixin';
import FormDesignMixin from '@src/mixins/formDesign';
import getProductField from '@src/modules/setting/task/taskFieldsSetting/TaskFieldsSetting';
/* api */
import * as SettingCusProApi from '@src/api/SettingCusProApi';
/* util */
import * as FormUtil from '@src/component/form/util';
import { parse } from '@src/util/querystring'
/* mixin */
import ThemeMixin from '@src/mixins/themeMixin/index.ts'
import { openAccurateTab } from '@src/util/platform'
import { PageRoutesTypeEnum } from 'pub-bbx-global/pageType/dist/enum/PageRoutesEnum'
export default {
  name: 'customer_card_setting',
  mixins: [fieldMixin, FormDesignMixin, ThemeMixin, getProductField],
  props: {
    initData: {
      type: Object,
      default: () => ({})
    }
  },
  data() {
    return {
      maxField: this.initData.fieldNum,
      init: false,
      loading: true,
      pending:false,
      cloneName:'',
      cardName:'',
      cardId:'',
      fields:[],
      cardType:'',
      prevTabId:'',
      relationOptions: { // 关联查询字段关联项数据
        customerFields: [],
        productFields: []
      },
    }
  },
  mounted(){
    let query = parse(window.location.search) || {};
    this.cardId = query.id;
    const name = decodeURIComponent(query.name);
    this.cloneName = name;
    this.cardName = name;
    this.cardType = query.cardType;
    this.prevTabId = query.prevTabId

    this.initFieldsData();
  },
  methods: {
    // 初始化表单字段
    async initFieldsData() {
      try {
        // 获取表单字段列表
        let {result} = await SettingCusProApi.getCardFieldList({ id: this.cardId, cardType: this.cardType });
        let sortedFields = result.sort((a, b) => a.orderId - b.orderId);
        
        this.fields = FormUtil.toFormField(sortedFields);
        this.loading = false;
      } catch (error) {
        this.loading = false;
      }
    },
    // 返回
    back(){
      let id = window.frameElement.dataset.id
      this.$platform.closeTab(id)

      const pageType = this.cardType === 'product' ? PageRoutesTypeEnum.PageProductAdditionalManage : PageRoutesTypeEnum.PageCustomerAdditionalManage;

      openAccurateTab({
        type: pageType,
        reload: false,
      })
    },
    /** 
    * @description 提交表单字段设置
    */
    async submit() {
      try {
        if(this.cardName !== this.cloneName ){
          let res = await this.updateTaskCardName({id: this.cardId, name: this.cardName});
          console.log(res);
          if(res.code !== 0){
            return this.$message.warning(res.message);
          }
        }
        let fields = FormUtil.toField(this.fields);
        fields.forEach((field, index) => {
          field.cardId = this.cardId;
          field.orderId = index;    
        });

        let message = FormUtil.validate(fields);
        if(!FormUtil.notification(message, this.$createElement)) return;

        this.pending = true;
        const params={
          cardId:this.cardId,
          cardType:this.cardType,
          cardFields:fields
        }
        let result = await SettingCusProApi.fieldEdit(params);

        let isSuccess = result.code == 0;
        this.$platform.notification({
          type: isSuccess ? 'success' : 'error',
          title: this.$t('customer.setting.customerAddcardFormView.tips1', {data1:isSuccess ? this.$t('common.base.success') : this.$t('common.base.fail')}),
          message: isSuccess ? null : result.message
        })
        if(isSuccess){
          setTimeout(()=>{
            this.back();
          }, 500)
        }
      } catch (error) {
        console.error(error)
      }

      this.pending = false;
    },

    // 更新组件名称
    updateTaskCardName() {
      const params={
        cardType:this.cardType,
        id: this.cardId,
        name: this.cardName
      }
      return SettingCusProApi.cardSave(params).then(res=>{
        return res
      }).catch(error=>({}))
    }
  }
}